#!/usr/bin/env python3
"""
Grafana MCP Server

面向软件：grafana
所有 MCP tool 列表：
- grafana_service_restart: 重启 grafana-server 服务
- grafana_service_reload: 重载 grafana-server 服务  
- grafana_service_status: 检查 grafana-server 服务状态

返回统一 JSON 结构：
{
  "success": bool,
  "command": str,
  "exit_code": int,
  "stdout": str,
  "stderr": str
}
"""

import subprocess
import json
from typing import Dict, Any
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Grafana MCP Server")

@mcp.tool()
def grafana_service_restart() -> Dict[str, Any]:
    """
    重启 grafana-server 服务
    
    返回:
        JSON 结构: {
            "success": bool,  # 命令是否成功执行
            "command": str,   # 执行的命令
            "exit_code": int, # 退出码
            "stdout": str,    # 标准输出
            "stderr": str     # 标准错误
        }
    """
    command = ["systemctl", "restart", "grafana-server.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def grafana_service_reload() -> Dict[str, Any]:
    """
    重载 grafana-server 服务
    
    返回:
        JSON 结构: {
            "success": bool,  # 命令是否成功执行
            "command": str,   # 执行的命令
            "exit_code": int, # 退出码
            "stdout": str,    # 标准输出
            "stderr": str     # 标准错误
        }
    """
    command = ["systemctl", "reload", "grafana-server.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def grafana_service_status() -> Dict[str, Any]:
    """
    检查 grafana-server 服务状态
    
    返回:
        JSON 结构: {
            "success": bool,  # 命令是否成功执行
            "command": str,   # 执行的命令
            "exit_code": int, # 退出码
            "stdout": str,    # 标准输出
            "stderr": str     # 标准错误
        }
    """
    command = ["systemctl", "status", "grafana-server.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

if __name__ == "__main__":
    mcp.run()